<!-- 编辑弹窗 -->
<template>
    <ele-modal
      width="1040px"
      :visible="visible"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改产品信息' : '添加产品信息'"
      @update:visible="updateVisible"
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
        <el-card  style="margin-top: -10px">
            <el-row :gutter="20">
                <el-col :md="8" :sm="24">
                    <el-form-item label="产品编号:">
                      <el-input v-model="form.code" placeholder="不填系统自动生成"   >
                         
                      </el-input>
                    </el-form-item>
                  </el-col>
                <el-col :md="16" :sm="24" >
                  <el-form-item label="产品名称:" prop="name"> 
                    <el-input v-model="form.name"  placeholder="请输入产品名称" />
                  </el-form-item>
                </el-col>
              </el-row>
      
          <el-row :gutter="15">
            <el-col :md="8" :sm="24">
            <el-form-item label="产品分类:" prop="categoriesId">
                <ele-tree-select
                      :data="treeData"
                      v-model="form.categoriesId"
                      :clearable="true"
                      placeholder="请选择"
                      :default-expand-all="true"
                    />
             
            </el-form-item>
           </el-col>
            <el-col :md="8" :sm="24">
              <el-form-item label="品牌:">
                <el-input v-model="form.brand" placeholder="请输入品牌" />
              </el-form-item>
            </el-col>
            <el-col :md="8" :sm="24">
                <el-form-item label="产地:">
                  <el-input v-model="form.place" placeholder="请输入产地" />
                </el-form-item>
              </el-col>
      
          </el-row>
          <el-row :gutter="15">
            <el-col  :sm="24" :md="8" >
              <el-form-item label="产品规格:" prop="productItemName">
                <el-input v-model="form.productItemName" placeholder="请输入产品规格"   />
              </el-form-item>
            </el-col>
            <el-col  :sm="24" :md="8" >
                  <el-form-item label="是否精品:" prop="isBoutique">
                    <el-radio-group v-model="form.isBoutique">
                        <el-radio  v-for="(item, index) in isSysList" :key="index" :label="item.Key" :value="item.Key">{{item.Value}}</el-radio>
                  
                      </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col  :sm="24" :md="8" >
                <el-form-item label="产品状态:">
                    <el-radio-group v-model="form.status" prop="status">
                        <el-radio  v-for="(item, index) in statusList" :key="index" :label="item.Key" :value="item.Key">{{item.Value}}</el-radio>
                      </el-radio-group>
              </el-form-item>
            </el-col>
  
          
          </el-row>
          <el-row :gutter="15">
          
         
            <el-col :md="8" :sm="24">
                <el-form-item label="库存:" prop="stockQty">
                  <el-input v-model="form.stockQty" placeholder="请输入库存"  @keyup.native="form.stockQty = form.stockQty.replace(/[^\d.]/g,'');
                  form.stockQty = form.stockQty.replace(/\.{2,}/g,'.');
                  form.stockQty = form.stockQty.replace(/^\./g,'');
                  form.stockQty = form.stockQty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  form.stockQty = form.stockQty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                </el-form-item>
              </el-col>
              <el-col :md="8" :sm="24">
                <el-form-item label="单位:">
                    <el-select v-model="form.unitId" filterable allow-create clearable placeholder="单位"   class="ele-block" @change="unitchange" >
                        <el-option v-for="(item, index) in units" :key="index" :label="item.name" :value="item.id"/>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="8" :sm="24">
                <el-form-item label="虚拟已售:" prop="virtualSaleQty">
                  <el-input v-model="form.virtualSaleQty" placeholder="请输入虚拟已售" @keyup.native="form.virtualSaleQty = form.virtualSaleQty.replace(/[^\d.]/g,'');
                  form.virtualSaleQty = form.virtualSaleQty.replace(/\.{2,}/g,'.');
                  form.virtualSaleQty = form.virtualSaleQty.replace(/^\./g,'');
                  form.virtualSaleQty = form.virtualSaleQty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  form.virtualSaleQty = form.virtualSaleQty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                  
                </el-form-item>
              </el-col>
          </el-row>
          <el-row :gutter="15">
          
            <el-col :md="8" :sm="24">
              <el-form-item label="销售价:" prop="price">
                <el-input v-model="form.price" placeholder="请输入销售价" @keyup.native="form.price = form.price.replace(/[^\d.]/g,'');
                form.price = form.price.replace(/\.{2,}/g,'.');
                form.price = form.price.replace(/^\./g,'');
                form.price = form.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                form.price = form.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </el-col>
            <el-col :md="8" :sm="24">
                <el-form-item label="成本价:" prop="costPrice">
                  <el-input v-model="form.costPrice" placeholder="请输入成本价"  @keyup.native="form.costPrice = form.costPrice.replace(/[^\d.]/g,'');
                  form.costPrice = form.costPrice.replace(/\.{2,}/g,'.');
                  form.costPrice = form.costPrice.replace(/^\./g,'');
                  form.costPrice = form.costPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  form.costPrice = form.costPrice.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"/>
                </el-form-item>
              </el-col>
              <el-col :md="8" :sm="24">
                <el-form-item label="门市价:" prop="shopPrice">
                  <el-input v-model="form.shopPrice" placeholder="请输入门市价"  @keyup.native="form.shopPrice = form.shopPrice.replace(/[^\d.]/g,'');
                  form.shopPrice = form.shopPrice.replace(/\.{2,}/g,'.');
                  form.shopPrice = form.shopPrice.replace(/^\./g,'');
                  form.shopPrice = form.shopPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  form.shopPrice = form.shopPrice.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
            <el-col  :sm="24" >
              <el-form-item label="产品图片:" >
                <el-upload action="#" ref="upload" list-type="picture-card"   :auto-upload="false" :file-list="fileList"  :class="{hide:hideUpload}" :disabled="fileList.length>=limit" :on-change="handleChange" :limit="limit">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}" style="width:100%;height:100%">
                      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" >
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" >
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span v-if="!removeDisable" class="el-upload-list__item-delete" @click="handleRemove(file)" >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible" style="z-index:9999" :modal="false">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
       
          <el-row :gutter="20">
            <el-col  :sm="24">
              <el-form-item label="产品详情:"  prop="content" style="width:100%" >
                <tinymce-editor v-model="form.content" :init="initData"/>
              </el-form-item>
              
             </el-col>
           
            
          </el-row>   
    
        </el-card>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </div>
    </ele-modal>
  </template>
  
  <script>
    //初始化对像
    import moment from "moment";
    import upload from "@/components/UpLoad/index.js";
    import { QueryAttchmentByExtendId ,GetGuid,UploadFile}  from '@/api/attchment';
    import { QueryIsSysEnum,QueryProductStatusEnum } from '@/api/enummanger';
    import TinymceEditor from '@/components/TinymceEditor';
    import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictionarymanager';
    import { QueryBProductViewById,AddProduct, UpdateProduct } from '@/api/productmanager/productmanager';
    import { QueryProductCategroyTree} from '@/api/productmanager/productcategorytmanager';
    export default {
      name: 'ProductEdit',
      components: {TinymceEditor},
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        
      },
      mixins: [upload],
      data() {
        return {
          // 表单数据
          form: {},
          // 表单验证规则
          rules: {
            name: [{required: true,message: '请输入产品名称',trigger: 'blur'}],
            categoriesId: [{required: true,message: '请选择产品分类',trigger: 'blur'}],
            productItemName: [{required: true,message: '请输入产品规格',trigger: 'blur'}],
            stockQty: [{required: true,message: '请输入库存',trigger: 'blur'}],
            virtualSaleQty:[{required: true,message: '请输入虚拟数量',trigger: 'blur'}],
            price: [{required: true,message: '请输入销售价',trigger: 'blur'}],
            costPrice: [{required: true,message: '请输入成本价',trigger: 'blur'}],
            shopPrice: [{required: true,message: '请输入门市价',trigger: 'blur'}],
            status: [{required: true,message: '请选择状态',trigger: 'blur'}],
            isBoutique: [{required: true,message: '请设置是否精品',trigger: 'blur'}],
          },
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
         
          //富文本框初始数据
        initData: {
          height: 500,
          //去掉图片的宽、高
          image_dimensions: false,
          images_upload_handler: (blobInfo, success, failure) => {
           
            //上传力图片对像
            let fdata = new FormData()
            fdata.set('imgType', 41); //图片类型
            fdata.set('attType', 1); //文件类型
            fdata.set('orderIndex', 510); // 顺序
            fdata.set('file', blobInfo.blob());
            fdata.set('fileName', blobInfo.blob().name); // 文件名称
            
            //上传图片
            UploadFile(fdata).then((res) => {
              if(res!=null && res!=undefined){
                success(res.fileAllPath)
              }else{
                failure(res.msg);
              }
            }).catch(e => {
              this.$message.error(e.message)
            })
          },
        },
          //性别
          isSysList:[],
          statusList:[],
          units:[],
          treeData:[]
        };
      },
      created(){
        this.limit = 1;
        this.getTreeData();
        this.queryIsSysEnums();
        this.queryQueryProductEnums();
        this.queryAllChildDictViewByCodes();
      },
       //初始化数据
      mounted(){
        this.limit = 1;
      },
      methods: {
        async getId(){
            let id = await GetGuid();
            this.form.id = id;
            let itemid = await GetGuid();
            this.form.productItemId=itemid;
        },
        async queryAllChildDictViewByCodes(){
            let unitsData = await  QueryAllChildDictViewByCode(this.Constant.C_DW);
            this.units = [];
            this.units = unitsData;
        },
       async queryIsSysEnums(){
        let sysEnums = await QueryIsSysEnum();
           console.log(sysEnums);
          sysEnums.map(e=>{
            this.isSysList.push({Key:e.Key,Value:e.Value});
          });
        },
        async queryQueryProductEnums(){
        let sysEnums = await QueryProductStatusEnum();
         
          sysEnums.map(e=>{
            this.statusList.push({Key:e.Key,Value:e.Value});
          });
        },
        
        async getTreeData(){
         await QueryProductCategroyTree().then((data)=>{
            console.log(data);
            this.treeData = data;
          });;
        },
           //单位选择
        unitchange(val){
          let currUnit = this.units.find((m)=>{
            return m.id == val;
          });

          if(!currUnit){
            this.form.unitName =val;
          }else{
            this.form.unitId = val;
            this.form.unitName =currUnit.name;
          }
        },
        /* 保存编辑 */
        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}
            //日期时间
            this.loading = true;

            //上传图片
            this.fileList.map((f) => {
            if (f.file != undefined) {
              f.fileType = 1;
              f.imgType = 4;
              console.log(f);
              this.uploadImg(f);
            }
          });
          if(this.form.unitId && this.form.unitId==this.form.unitName) this.form.unitId = '';
            const saveOrUpdate = this.isUpdate ? UpdateProduct : AddProduct;
            console.log(this.form);
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
  
                //回调父组件方法
                this.$emit('done');
                this.fileList = [];
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },
        setData(id){
            QueryBProductViewById(id)
            .then((res) => {
              this.form=res;
              //this.$util.assignObject(this.form, {...res});
               
           });
        },
        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
          //更新文件列表对像
          this.fileList= [];
        },
  
        //赋值到附件
        setAttchement(id,itemid){
            QueryAttchmentByExtendId(itemid).then((d)=>{
            this.fileList = [];
            d.map((item)=>{
              this.fileList.push({
                id: item.id,
                name: item.fileName,
                url: item.fileAllPath,
                businessId: item.businessId,
                extendId:item.extendId,
                orderIndex: item.orderIndex,
              });
            });
             //设置上传图片按钮是否可见
             if(this.fileList!=null && this.fileList!=undefined){
                this.hideUpload = this.fileList.length >= this.limit;
              }else{
                this.hideUpload =false;
              }
          });
        },
        //上传图片
        handleChange(file, fileList) {
          this.noneUploadImg = fileList.length >= this.limit;
          let obj = {
            orderIndex: 1, //默认值
            attType: 1, //文件类型(1:图片,2:文件)
            file: file.raw, // 文件流
            fileName: file.name, // 文件名称
            url:file.url,// 文件路径
          }
          //索引
          if(fileList!=null && fileList.length>0){
            obj.orderIndex = fileList.length;
          }
          //业务id 新增页面时，从后台获取Guid
          if(this.form){
            obj.businessId = this.form.id; 
            obj.extendId=this.form.productItemId;
          }
          //文件列表
          this.fileList.push(obj);
           //设置上传图片按钮是否可见
           if(this.fileList!=null && this.fileList!=undefined){
                this.hideUpload = this.fileList.length >= this.limit;
              }else{
                this.hideUpload =false;
              }
        },
  
      },
 
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.form={};
              this.setData(this.data.productItemId);
              this.setAttchement(this.data.id,this.data.productItemId);
              this.isUpdate = this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={}
              this.getId();
              this.form.content='';
              this.isUpdate = false;
            }
          } else {
             //设置上传图片按钮是否可见
             if(this.fileList!=null && this.fileList!=undefined){
                this.hideUpload = this.fileList.length >= this.limit;
              }else{
                this.hideUpload =false;
              }
              this.form.content='';
            //移除校验结果
            this.$refs['form'].clearValidate();
            this.form = {};
          }
        }
      }
    };
  </script>
  <style scoped>
    .hide .el-upload-picture-card{
      display:none
    }
.el-upload-list__item.is-ready {
       display: none !important;  /* 防止上传时候的页面抖动*/
}
    </style>
    
  